#pragma once
#include<iostream>
#include<cstring>
#include<unistd.h>
#include<vector>

namespace wyl
{
    std::vector<int> Socks;

    class Task
    {
    private:
        int sock_;
        std::string ip_;
    public:
        Task(): sock_(-1),ip_("erro"){};
        Task(int sock,std::string ip): sock_(sock),ip_(ip){};

        void Run()
        {
            char buff[1024];
            Socks.push_back(sock_);
            for(; ;)
            {
                memset(buff,0,sizeof buff);
                int s = read(sock_,buff,sizeof(buff) - 1);
                if(s == 0) break;
                else if(s < 0)
                {
                    std::cerr << "read error  " << errno << std::endl;
                    break;
                }
                buff[s] = 0;
                std::cout << "client ##" << buff << std::endl;

                //返回给客户端
                std::string message = ip_ + " say :";
                message += buff;

                //write(sock_,message.c_str(),message.size());
                //转发所有消息给连接了的客户端
                for(auto& e : Socks)
                {
                    if(e != sock_)
                        write(e,message.c_str(),message.size());
                }
            }
            close(sock_);
            std::vector<int>::iterator it = Socks.begin();
            while(*it != sock_)
                it++;
            Socks.erase(it);
        }

        ~Task() {};
    };

    
}